package com.mlink.ai.chat.utils

import android.content.Context
import androidx.annotation.ArrayRes
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.mlink.ai.chat.assistant.robot.R
import com.mlink.ai.chat.bean.ExploreCategory
import com.mlink.ai.chat.bean.ExploreSubCategory
import com.mlink.ai.chat.ui.activity.PromptCreateActivity
import com.tencent.mmkv.MMKV

object PromptUtils {

    const val PROMPT_CREATE_ITEM_ID = 0L

    private const val KEY_JSON_CUSTOM_PROMPT_CATEGORIES = "json_custom_prompt_categories"

    private const val KEY_PROMPT_CREATE_COUNT = "prompt_create_count"

    /**
     * 获取所有的 Prompt List
     */
    fun getPromptCategoryList(context: Context): List<ExploreCategory> {
        val customList = getCustomPromptCategoryList()
        val buildInList = getPresetPromptCategoryList(context)
        return mergeData(customList, buildInList)
    }

    /**
     * 获取自定义 Prompt （包含内置大分类添加子分类的情况）
     */
    fun getCustomPromptCategoryList(): List<ExploreCategory> {
        val json = MMKV.defaultMMKV().decodeString(KEY_JSON_CUSTOM_PROMPT_CATEGORIES, "")
        if (json.isNullOrEmpty()) {
            return ArrayList()
        }
        return Gson().fromJson<ArrayList<ExploreCategory>?>(
            json,
            object : TypeToken<List<ExploreCategory>>() {}.type
        )
    }

    /**
     * 获取内置的 Prompt List
     */
    fun getPresetPromptCategoryList(context: Context): List<ExploreCategory> {
        val list = ArrayList<ExploreCategory>()
        val categoryIdList = getPresetCategoryIdList(context)
        val categoryNameList = getPresetCategoryNameList(context)
        val subCategoryNameMappingList = getPresetSubCategoryNameMappingList(context)
        val subCategoryDescMappingList = getPresetSubCategoryDesMappingList(context)
        val subCategoryPromptMappingList = getPresetSubCategoryPromptMappingList(context)
        val categoryEventNameList = getPresetCategoryEventNameList(context)
        val subCategoryEmojiMappingList = getPresetSubCategoryEmojiMappingList(context)
        for (categoryNameIndex in categoryNameList.indices) {
            val id = categoryIdList[categoryNameIndex]
            val category = ExploreCategory(id, categoryNameList[categoryNameIndex]).apply {
                categoryEventName = categoryEventNameList[categoryNameIndex]
            }

            val subCategoryNameArrayResourceId = context.getArrayIdentifier(
                subCategoryNameMappingList[categoryNameIndex]
            )
            val subCategoryNameList = getPresetSubcategoryNameList(context, subCategoryNameArrayResourceId)
            val subCategoryEventNameList = getPresetSubcategoryEventNameList(context, subCategoryNameArrayResourceId)

            val subCategoryDescArrayResourceId = context.getArrayIdentifier(
                subCategoryDescMappingList[categoryNameIndex]
            )
            val subCategoryDescList = getPresetSubcategoryDescList(context, subCategoryDescArrayResourceId)

            val subCategoryPromptArrayResourceId = context.getArrayIdentifier(
                subCategoryPromptMappingList[categoryNameIndex]
            )
            val subCategoryPromptList = getPresetSubcategoryPromptList(
                context,
                subCategoryPromptArrayResourceId
            )

            val subCategoryEmojiArrayResourceId = context.getArrayIdentifier(
                subCategoryEmojiMappingList[categoryNameIndex]
            )
            val subCategoryEmojiList = getPresetSubcategoryPromptList(
                context,
                subCategoryEmojiArrayResourceId
            )

            val subCategoryList = ArrayList<ExploreSubCategory>()
            for (subCategoryNameIndex in subCategoryNameList.indices) {
                val subCategory = ExploreSubCategory(
                    (subCategoryNameIndex + 1).toLong(),
                    subCategoryNameList[subCategoryNameIndex],
                    subCategoryDescList[subCategoryNameIndex],
                    subCategoryPromptList[subCategoryNameIndex],
                    categoryEventName = subCategoryEventNameList[subCategoryNameIndex],
                    emoji = subCategoryEmojiList[subCategoryNameIndex],
                    parentCategoryId = category.id
                )
                subCategoryList.add(subCategory)
                category.subCategories = subCategoryList
            }

            list.add(category)
        }

        return list
    }

    private fun mergeData(
        customList: List<ExploreCategory>,
        buildInList: List<ExploreCategory>
    ): List<ExploreCategory> {
        val resultMap = mutableMapOf<Long, ExploreCategory>()

        customList.forEach { data ->
            resultMap[data.id] = data
        }

        buildInList.forEach { data ->
            if (resultMap.containsKey(data.id)) {
                data.subCategories = resultMap[data.id]!!.subCategories + data.subCategories
                resultMap[data.id] = data
            } else {
                resultMap[data.id] = data
            }
        }

        val list = resultMap.values.toList()
        // 过滤出完全是自定义的 Prompt，并按 ID 降序排序
        val customPromptList = list.filter { it.isCustom }.sortedByDescending { it.id }
        // 过滤出完全是内置的 Prompt，并按 ID 升序排序
        val presetPromptList = list.filterNot { it.isCustom }.sortedBy { it.id }

        val sortedList = mutableListOf<ExploreCategory>()
        sortedList.addAll(customPromptList)
        sortedList.addAll(presetPromptList)

        return sortedList
    }

    fun saveCustomPromptCategoryList(list: List<ExploreCategory>) {
        MMKV.defaultMMKV()
            .encode(KEY_JSON_CUSTOM_PROMPT_CATEGORIES, Gson().toJson(list))
    }

    private fun getDefaultPresetCategoryId(context: Context): Long =
        context.resources.getIntArray(R.array.explore_categories_id)[0].toLong()

    fun getCategoriesMaxId(categoryList: List<ExploreCategory>): Long =
        categoryList.maxByOrNull { it.id }?.id ?: 0L

    fun getSubCategoriesMaxId(subCategoryList: List<ExploreSubCategory>): Long =
        subCategoryList.maxByOrNull { it.id }?.id ?: 0L

    fun saveCustomPromptList(list: List<ExploreCategory>) {
        MMKV.defaultMMKV().encode(KEY_JSON_CUSTOM_PROMPT_CATEGORIES, Gson().toJson(list))
    }

    fun savePromptCreateCount(createCount: Int) {
        MMKV.defaultMMKV().encode(KEY_PROMPT_CREATE_COUNT, createCount)
    }

    fun getPromptCreateCount() = MMKV.defaultMMKV().decodeInt(KEY_PROMPT_CREATE_COUNT, 0)

    fun getLastSelectedCategoryId(context: Context) = MMKV.defaultMMKV().getLong(
        PromptCreateActivity.KEY_LAST_SELECTED_CATEGORY_ID,
        getDefaultPresetCategoryId(context)
    )

    fun saveLastSelectedCategoryId(selectedId: Long) {
        MMKV.defaultMMKV().encode(PromptCreateActivity.KEY_LAST_SELECTED_CATEGORY_ID, selectedId)
    }

    fun getPresetCategoryIdList(context: Context) =
        context.resources.getIntArray(R.array.explore_categories_id).map { it.toLong() }

    private fun getPresetCategoryNameList(context: Context): List<String> =
        context.resources.getStringArray(R.array.explore_categories).toList()

    private fun getPresetCategoryEventNameList(context: Context): List<String> =
        context.getEnglishStringArray(R.array.explore_categories).toList()

    private fun getPresetSubCategoryNameMappingList(context: Context): List<String> =
        context.resources.getStringArray(R.array.explore_sub_categories_mapping).toList()

    private fun getPresetSubCategoryDesMappingList(context: Context): List<String> =
        context.resources.getStringArray(R.array.explore_sub_categories_desc_mapping).toList()

    private fun getPresetSubCategoryPromptMappingList(context: Context): List<String> =
        context.resources.getStringArray(R.array.explore_sub_categories_prompt_mapping).toList()

    private fun getPresetSubCategoryEmojiMappingList(context: Context): List<String> =
        context.resources.getStringArray(R.array.explore_sub_categories_emoji_mapping).toList()

    private fun getPresetSubcategoryNameList(context: Context, @ArrayRes resourceId: Int): List<String> =
        context.resources.getStringArray(resourceId).toList()

    private fun getPresetSubcategoryEventNameList(context: Context, @ArrayRes resourceId: Int): List<String> =
        context.getEnglishStringArray(resourceId).toList()

    private fun getPresetSubcategoryDescList(context: Context, @ArrayRes resourceId: Int): List<String> =
        context.resources.getStringArray(resourceId).toList()

    private fun getPresetSubcategoryPromptList(context: Context,@ArrayRes resourceId: Int): List<String> =
        context.resources.getStringArray(resourceId).toList()

}